from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Integer, Column, String, orm

db = SQLAlchemy()


class Book(db.Model):
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(50), nullable=False)
    author = Column(String(30), default='未名')
    binding = Column(String(20))
    publisher = Column(String(50))
    price = Column(String(20))
    pages = Column(Integer)
    pubdate = Column(String(20))
    isbn = Column(String(15), nullable=False, unique=True)
    summary = Column(String(1000))
    image = Column(String(100))

    @orm.reconstructor
    def __init__(self):
        self.fields = ['id', 'title', 'author', 'binding', 'publisher',
                       'price', 'pages', 'pubdate', 'isbn', 'summary', 'image']

    def keys(self):
        return self.fields

    def __getitem__(self, item):  # item会拿到keys函数返回的元组
        return getattr(self, item)  # 如果参数是 o , 'x' , 则返回 o.x


